package com.zjw.hyphenateui.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.havi.helper.ChatHelper;
import com.example.havi.interfaces.LoginCallBack;
import com.example.havi.ui.ChatActivity;
import com.example.havi.util.ChatSPUtil;
import com.example.havi.util.ChatToastUtil;
import com.example.havi.util.LogUtil;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversation;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageListener;
import com.tencent.imsdk.TIMUserStatusListener;
import com.tencent.imsdk.ext.message.TIMConversationExt;
import com.tencent.imsdk.ext.message.TIMManagerExt;
import com.zjw.hyphenateui.MainApplication;
import com.zjw.hyphenateui.R;
import com.zjw.hyphenateui.bean.UserBean;
import com.zjw.hyphenateui.helper.HyphenateLibraryCallBackHandle;
import com.zjw.hyphenateui.helper.NotificationConstants;
import com.zjw.hyphenateui.helper.NotificationHelper;
import com.zjw.hyphenateui.helper.UserHelper;
import com.zjw.hyphenateui.util.ToastUtil;
import com.zjw.hyphenateui.widget.NoScrollViewPager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.viewPager)
    NoScrollViewPager viewPager;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.unread_msg_number)
    TextView unreadMsgNumber;
    private List<Fragment> fragments;

    private final static int REQUEST_PHONE_PERMISSIONS = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initMenus();
        initView();

        //根据ID消除通知
        NotificationHelper.getInstance().cancelNotification(NotificationConstants.HYPHENATE_NOTIFCATION_ID);
        //注册一个监听连接状态的listener

    }



    //实现ConnectionListener接口
    private class MyUserStatusListener implements TIMUserStatusListener {
        @Override
        public void onForceOffline() {
            // 显示帐号在其他设备登录
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
            builder.setTitle("警告");
            builder.setMessage("账号异地登录！！");
            builder.setCancelable(false);
            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    startActivity(new Intent(MainActivity.this,LoginActivity.class));
                    ChatHelper.getInstance().loginOutTIM(new ChatHelper.LoginOutCallBack() {
                        @Override
                        public void loginOutSuccess() {

                        }

                        @Override
                        public void loginOutFailure(String errorMsg) {

                        }
                    });
                    ChatSPUtil.setString("chat_user", "");
                    ChatSPUtil.setString("chat_pwd", "");
                    finish();
                }
            });
            builder.show();
        }

        @Override
        public void onUserSigExpired() {
            // 显示帐号在其他设备登录
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
            builder.setTitle("警告");
            builder.setMessage("账号过期！！");
            builder.setCancelable(false);
            builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    startActivity(new Intent(MainActivity.this,LoginActivity.class));
                    ChatHelper.getInstance().loginOutTIM(new ChatHelper.LoginOutCallBack() {
                        @Override
                        public void loginOutSuccess() {

                        }

                        @Override
                        public void loginOutFailure(String errorMsg) {

                        }
                    });
                    ChatSPUtil.setString("chat_user", "");
                    ChatSPUtil.setString("chat_pwd", "");
                    finish();
                }
            });
            builder.show();

        }
    }

    String[] tabNames;
    int[] tabIcons;

    private void initMenus() {
        tabNames = getResources().getStringArray(R.array.main_tabs);
        TypedArray ar = getResources().obtainTypedArray(R.array.main_tab_icons);
        int len = ar.length();
        tabIcons = new int[len];
        for (int i = 0; i < len; i++) {
            tabIcons[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
    }

    private void initView() {
        fragments = new ArrayList<>();
        fragments.add(new MessageFragment());
        fragments.add(new SearchChatFragment());
        fragments.add(new MineFragment());
        viewPager.setOffscreenPageLimit(2);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

        });
        //设置图标
        tabLayout.setupWithViewPager(viewPager);
        for (int i = 0; i < tabNames.length; i++) {
            tabLayout.getTabAt(i).setCustomView(getTabView(tabNames[i], tabIcons[i]));
        }

        initChat();
        TIMManager.getInstance().getUserConfig().setUserStatusListener(new MyUserStatusListener());
    }

    public View getTabView(String tabName, int tabIcon) {
        View view = LayoutInflater.from(getBaseContext()).inflate(R.layout.tab_layout, null);
        ImageView iv_tab = view.findViewById(R.id.iv_tab);
        TextView tv_tab = view.findViewById(R.id.tv_tab);
        iv_tab.setImageResource(tabIcon);
        tv_tab.setText(tabName);
        return view;
    }


    @Override
    protected void onResume() {
        super.onResume();
        updateUnreadLabel();    //更新消息未读数
        TIMManager.getInstance().addMessageListener(messageListener);     //添加消息接收监听
    }

    @Override
    protected void onStop() {
        super.onStop();
        TIMManager.getInstance().removeMessageListener(messageListener); //移除消息接收监听
    }

    TIMMessageListener messageListener = new TIMMessageListener() {


        @Override
        public boolean onNewMessages(List<TIMMessage> list) {
            refreshUIWithMessage();
            return false;
        }
    };


    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                updateUnreadLabel();
                //如果一级界面是会话列表 在这里调用方法更新
                ((MessageFragment)fragments.get(0)).refresh();
            }
        });
    }


    /**
     * 更新消息未读数
     */
    private void updateUnreadLabel() {
        long unreadMessageCount = 0;
        List<TIMConversation> list = TIMManagerExt.getInstance().getConversationList();
        for (TIMConversation con: list)
        {
            TIMConversationExt conExt = new TIMConversationExt(con);
            unreadMessageCount = unreadMessageCount + conExt.getUnreadMessageNum();
        }
        int unreadMessageCountInt = (int) unreadMessageCount;
        if((int)unreadMessageCount>0){
            unreadMsgNumber.setText(unreadMessageCountInt+"");
            unreadMsgNumber.setVisibility(View.VISIBLE);
        }else{
            unreadMsgNumber.setVisibility(View.INVISIBLE);
        }
    }



    private static ChatHelper chatHelper;
    //初始化环环信库
    private void initHyphenateIM() {
        //初始化
        chatHelper = ChatHelper.getInstance();
        chatHelper.init(getApplicationContext(),new HyphenateLibraryCallBackHandle(),"1400135165");
//        if (user.equals("tsw1") && pwd.equals("123456")) {
            final String identifier = "BPRP0913114514";
            final String usersig = "eJxNjtFOg0AQRf*FV43sLLtQTfqAiEUiFmqpNSEhBLa4tsIWlrbE9N*7Ekw6j*fcmbm-2vL1-S7L87qrZCp7wbQHDWm3A*YFqyTfcNYo*BguQnQPBgChQMZEJgQv0kymRlNcLbbFNh2UYkAQAoOCSUfJToI3LM02crg7MVVAzWgPrGl5XSmBEVDAxrWU-OevH1CCwTIta-L-j5cKB27kvLh5SdtEX*F95bnPpFt-OZ1HSi84dg3Mw92SxPSbHeU6fkM2t-FTojs03M5votlp8UF7EQe*H-UOres9m60wxT6LBfncJbo9nWrnC6daWNo_";
            MainActivity.getChatHelper().login(identifier, usersig, new LoginCallBack() {
                @Override
                public void onSuccess() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(getBaseContext(), "登录成功");
                            UserBean userBean = new UserBean();
                            userBean.setChatId(identifier);
                            userBean.setNickName("tsw1");
                            userBean.setUserId("BPRP0913114514");
                            userBean.setChatPwd(usersig);
                            UserHelper.login(userBean);
                            ToastUtil.showToast(getBaseContext(), "登录成功：" + identifier);
                            finish();
                        }
                    });
                }

                @Override
                public void onError(int code, final String message) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ToastUtil.showToast(getBaseContext(), "登录失败：" + message);
                        }
                    });

                }
            });
//        } else if (user.equals("tsw2") && pwd.equals("123456")) {
//
//            final String identifier = "MPOX1114165201";
//            final String usersig ="eJxNjlFPg0AQhP-LvWqE4zgkJj60iLXVliYWJYSEXLil3RIBj7PSGv*7V4JJ93G*mZ35IZuX1xtRFM1XrXN9bIHcEZtcDzJKqDWWCMqIy3WUUEpd6nHHpqNDtC3KXOicKXkR7GSVD8ho1LVtyriJjRD6FhXkotTDX98zBnMjPYDqsKkNMC2cOuwSavw476PcdajPueP-9*H2vDCMg-kDn6NOk4X*3i3h5J1m-TSzoEz6sPjMrLdq9dxXqR9HjyICmGA42e*eMus9PMgZBmzRRGwfXEGwjlm62kzBTZS81UmZNluwu3vy*wf9Dlpk";
//            MainActivity.getChatHelper().login(identifier, usersig, new LoginCallBack() {
//                @Override
//                public void onSuccess() {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            progressFl.setVisibility(View.GONE);
//                            ToastUtil.showToast(getBaseContext(), "登录成功");
//                            UserBean userBean = new UserBean();
//                            userBean.setChatId(identifier);
//                            userBean.setNickName("tsw2");
//                            userBean.setUserId(identifier);
//                            userBean.setChatPwd(usersig);
//                            UserHelper.login(userBean);
//                            startActivity(new Intent(getBaseContext(), MainActivity.class));
//                            finish();
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, final String message) {
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            progressFl.setVisibility(View.GONE);
//                            ToastUtil.showToast(getBaseContext(), "登录失败：" + message);
//                        }
//                    });
//
//                }
//            });
//        } else {
//            Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show();
//        }

    }

    public static ChatHelper getChatHelper(){
        return chatHelper;
    }



    private void initChat() {
        final List<String> permissionsList = new ArrayList<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.READ_PHONE_STATE);
            if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (permissionsList.size() == 0) {
               initHyphenateIM();
            } else {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_PHONE_PERMISSIONS);
            }
        } else {
            initHyphenateIM();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_PHONE_PERMISSIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                   initHyphenateIM();
                } else {
                    Toast.makeText(this, "需要先同意权限", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
